#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define N 32

int main(){
    int serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    struct sockaddr_in serv_addr;
    char buffer[N];
    int len;

    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    serv_addr.sin_port = htons(54321);

    bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

    listen(serv_sock, 5);
    struct sockaddr_in clnt_addr;
    socklen_t clnt_addr_size = sizeof(clnt_addr);
    while (1) {
        printf("server is listening...\n");
        int clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size);
        if (clnt_sock < 0) {
            break;
        }

        while (1) {
            len = read(clnt_sock, buffer, N);
            if (len <= 0) {
                printf("client %d exit.\n", clnt_sock);
                close(clnt_sock);
                break;
            }
            printf("recv: %s\n", buffer);
            write(clnt_sock, buffer, len);
        }
    }
   
    close(serv_sock);
    return 0;
}

